import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElCard, ElFormItem, ElInput, ElSelect, ElOption, ElDatePicker } from 'element-plus'

import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { alarmNameEnum, fnStateEnum } from '~/store/monitor/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import ColorfulBadge from '~/components/ColorfulBadge'
import dayjs from 'dayjs'

export default defineComponent(function LampAlarm() {
  const store = useStore()
  const router = useRouter()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const policeState = useVuexGetters('police', [
    'alarmNameOpt',
    'workAreaOpt',
    'alarmStatusOpt',
    'alarmStatusEnum',
    'ignoreStatusOpt',
    'ignoreStatusEnum'
  ])

  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '警报名称',
      prop: 'alarmName',
      minWidth: 160,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '警报时间',
      prop: 'reportTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '警报状态',
      prop: 'alarmState',
      minWidth: 160,
      showOverflowTooltip: true,
      enumValues: policeState.alarmStatusEnum,
      align: 'center',
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.alarmState as unknown as number}
          options={{ success: 0, warning: 1 }}
        />
      )
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备编号',
      prop: 'deviceCode',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '所属灯杆',
      prop: 'lampPostName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '品牌名称',
      prop: 'brandName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '忽略状态',
      prop: 'ignoreState',
      minWidth: 160,
      showOverflowTooltip: true,
      enumValues: policeState.ignoreStatusEnum,
      align: 'center',
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.ignoreState as unknown as number}
          options={{ success: 1, info: 0 }}
        />
      )
    },
    {
      label: '恢复时间',
      prop: 'recoverTime',
      minWidth: 160,
      hidden: true,
      showOverflowTooltip: true,
      sortable: true
    }
  ]

  onMounted(() => {
    //  警报名称
    store.dispatch('police/SelectAlarmBoxList')
    //  所属工区
    store.dispatch('police/SelectAreaNameBoxList')
    //  警报状态
    store.dispatch('police/AlarmStatusOpt', { code: 'device_alarm_state' })
    //  忽略状态
    store.dispatch('police/IgnoreStatusOpt', { code: 'device_alarm_ignoreState' })

    const row: FormValuesType = router.currentRoute.value.query
    if (row.deviceName) {
      // formValues.keyWord = row.deviceName
    }
    if (row.alarmName) {
      formValues.alarmName = row.alarmName
    }
    if (row.deviceName || row.alarmName) {
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 500)
    }
  })

  //  按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  //  清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          proSaasTableRef.value!?.toSearch()
        }, 100)
      }
    }

    return (
      <ElCard>
        <ProSaasTable<FormValuesType>
          tableId="monitor_police_data_index"
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{
            times: undefined,
            beginTime: formValues.times?.[0] ? dayjs(formValues.times?.[0]).valueOf() : '',
            endTime: formValues.times?.[1] ? dayjs(formValues.times?.[1]).valueOf() : ''
          }}
          hasSelection
          dispatchType="singleLamp/AlarmlistPage"
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="keyWord" prop="keyWord" label="">
              <ElInput
                v-model={formValues.keyWord}
                placeholder="设备名称或设备编号"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="alarmName" prop="alarmName">
              <ElSelect
                v-model={formValues.alarmName}
                clearable
                placeholder="请选择警报名称"
                onChange={clearSearchTable}
                filterable
              >
                {policeState.alarmNameOpt?.value?.map((item: alarmNameEnum) => (
                  <ElOption key={item?.id} label={item?.alarmName} value={item?.alarmName} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="alarmState" prop="alarmState">
              <ElSelect
                v-model={formValues.alarmState}
                clearable
                placeholder="请选择警报状态"
                onChange={clearSearchTable}
              >
                {policeState.alarmStatusOpt?.value?.map((item: fnStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="ignoreState" prop="ignoreState">
              <ElSelect
                v-model={formValues.ignoreState}
                clearable
                placeholder="请选择忽略状态"
                onChange={clearSearchTable}
              >
                {policeState.ignoreStatusOpt?.value?.map((item: fnStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="times" prop="times">
              <ElDatePicker
                v-model={formValues.times}
                start-placeholder="警报开始时间"
                end-placeholder="警报结束时间"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                {...props}
              />
            </ElFormItem>
          ]}
        />
      </ElCard>
    )
  }
})
